


package yf.mall.controller.app;

import com.yf.request.SearchParam;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.yf.response.RRException;
import com.yf.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yf.annotation.SysLog;
import yf.mall.entity.DyAccountAuthEntity;
import yf.mall.entity.KolOrderStatEntity;
import yf.mall.service.app.DyAccountAuthService;
import yf.mall.utils.app.AppUtil;
import yf.mall.vo.KolOrderStatVo;
import yf.mall.service.app.KolOrderStatService;
import com.yf.response.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;


@Slf4j
@RestController
@RequestMapping("/kol/order/stat")
public class KolOrderStatController {
    @Autowired
    private KolOrderStatService kolOrderStatService;

    @Resource
    private DyAccountAuthService dyAccountAuthService;

    @RequestMapping("/list")
    @RequiresPermissions("kol:order:stat:list")
    public R list(@RequestBody SearchParam<KolOrderStatVo> params) {
        PageHelper.startPage(params.getPage(), params.getLimit()).setOrderBy(params.getOrder());
        List<KolOrderStatVo> list = kolOrderStatService.findVo(params.getEntity());
        return R.ok(new PageInfo(list));
    }

    @RequestMapping("/down")
    @RequiresPermissions("kol:order:stat:list")
    public void down(@RequestBody SearchParam<KolOrderStatVo> params, HttpServletResponse response) {
        List<KolOrderStatVo> list = kolOrderStatService.findVo(params.getEntity());
        kolOrderStatService.downLoad(response, list);
    }

    @RequestMapping("/upload")
    public void upload(MultipartFile file) {
        try {
            kolOrderStatService.upload(file.getInputStream());
        } catch (IOException e) {
            throw new RRException("上传的文件有误!");
        }
    }


    @RequestMapping("/info/{id}")
    @RequiresPermissions("kol:order:stat:info")
    public R info(@PathVariable("id") Long id) {
        KolOrderStatVo vo = kolOrderStatService.getVo(id);

        return R.ok(vo);
    }

    @RequestMapping("/save")
    @RequiresPermissions("kol:order:stat:save")
    public R save(@RequestBody KolOrderStatVo vo) {
        kolOrderStatService.saveVo(vo);
        return R.ok(vo);
    }

    @RequestMapping("/update")
    @RequiresPermissions("kol:order:stat:update")
    public R update(@RequestBody KolOrderStatVo vo) {
        kolOrderStatService.updateVo(vo);

        return R.ok(vo);
    }

    @RequestMapping("/delete")
    @RequiresPermissions("kol:order:stat:delete")
    public R delete(Long[] ids) {
        kolOrderStatService.deleteBatch(ids);

        return R.ok();
    }

    @RequestMapping("/all")
    public R all(String order) {
        PageHelper.orderBy(order != null ? order : "id desc");
        List<KolOrderStatVo> list = kolOrderStatService.findVo(null);
        return R.ok(list);
    }

    @RequestMapping("/dmz/options")
    public R options() {
        HashMap<String, Object> options = new HashMap();
        return R.ok(options);
    }


    /***********自定义开始***********/

    @RequestMapping("/dmz/update-order-stat")
    public R updateOrderStat(Long userId, String beginStr) {
        Date begin = null;
        try {
            begin = DateUtil.strToDate(beginStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if (userId == null) {
            return R.error("请输入需要更新的用户id");
        }
        if (begin == null) {
            return R.error("请输入开始时间");
        }
        DyAccountAuthEntity authEntity = dyAccountAuthService.getMasterAuthByUserId(userId);
        if (authEntity == null) {
            return R.error("该用户未授权绑定数据，请先授权绑定");
        }
        String openId = authEntity.getOpenId();
        List<KolOrderStatEntity> kolOrderStatEntities = kolOrderStatService.calOrderStatByOrderWithRange(openId, begin, new Date());

        List<KolOrderStatEntity> dbOrderStatEntities = kolOrderStatService.findOrderStatByOpenIds(Arrays.asList(openId), AppUtil.getIntegerDate(begin), null, null, 30);
        Map<Integer, KolOrderStatEntity> orderStatByDateMap = dbOrderStatEntities.stream().collect(Collectors.toMap(KolOrderStatEntity::getDate, Function.identity()));
        for (KolOrderStatEntity kolOrderStatEntity : kolOrderStatEntities) {
            log.info("更新订单统计数据，kolOrderStatEntity={}", kolOrderStatEntity);
            if (!orderStatByDateMap.containsKey(kolOrderStatEntity.getDate())) {
                kolOrderStatService.save(kolOrderStatEntity);
            } else {
                KolOrderStatEntity dbKolOrderStat = dbOrderStatEntities.get(0);
                kolOrderStatEntity.setId(dbKolOrderStat.getId());
                kolOrderStatService.update(kolOrderStatEntity);
            }
        }
        return R.ok();
    }
}
